<template>
  <!-- 页面-角色管理 -->
  <div class="RoleManage-page innerPageTable-out-flex"
    :class="{'innerPageTable-box-OneTwo': !useTableSearchBar}"
  >
    <!-- 搜索区域 -->
    <SelfAdaption v-if="!useTableSearchBar">
      <Form
        :model="searchForm"
        ref="roleFormSearch"
        slot="adaption-bar"
        label-position="top"
        class="ivu-form-no-margin-bottom"
        inline
      >
        <template>
          <!-- 角色编码 -->
          <Form-item prop="roleCode" :label="$t('module.role.roleCode')">
            <Input
              type="text"
              :maxlength="30"
              v-model.trim="searchForm.roleCode"
              :placeholder="$t('module.role.warning.enterRoleCode')"
              @on-enter="search"
            ></Input>
          </Form-item>

          <!-- 角色名称 -->
          <Form-item prop="roleName" :label="$t('module.role.roleName')">
            <Input
              type="text"
              :maxlength="30"
              v-model.trim="searchForm.roleName"
              :placeholder="$t('module.role.warning.enterRoleName')"
              @on-enter="search"
            ></Input>
          </Form-item>

          <!-- 角色类型 -->
          <Form-item :label="$t('module.role.roleType')">
            <Select
              style="width: 100%;"
              v-model.trim="searchForm.roleType"
              :placeholder="$t('module.role.warning.selectRoleType')"
              clearable
            >
              <Option v-for="(item, index) in searchRolTypeList" :value="item.vsiKey" :key="index">{{
                item.vsiValue
              }}</Option>
            </Select>
          </Form-item>

          <!-- 功能组编码 -->
          <Form-item prop="menuCode" :label="$t('module.role.menuCode')">
            <Input
              type="text"
              :maxlength="30"
              v-model.trim="searchForm.menuCode"
              :placeholder="$t('module.role.warning.enterMenuCode')"
              @on-enter="search"
            ></Input>
          </Form-item>

          <!-- 状态 -->
          <Form-item prop="enabled" :label="$t('common.status')">
            <Select
              style="width: 100%;"
              v-model.trim="searchForm.enabled"
              :placeholder="$t('common.warning.selectStatus')"
              clearable
            >
              <Option v-for="(item, index) in searchStatusList" :value="item.vsiKey" :key="index">{{
                item.vsiValue
              }}</Option>
            </Select>
          </Form-item>

          <!-- 查询\重置按钮 -->
          <Form-item prop="button" class="search-solt-btn">
            <RPButton optType="search" @click="search" />
            <RPButton optType="reset" @click="reset" />
          </Form-item>
        </template>
      </Form>
    </SelfAdaption>
    <InnerPageTable ref="roleTable" :config="tableConfig" v-if="this.userRolePermission || this.appRolePermission">
      <!-- handler bar 查询/重置-->
      <!--
      <div slot="handle-bar">
        <RPButton optType="search" @click="search" />
        <RPButton optType="reset" @click="reset" />
      </div>
      -->
      <!-- table bar 添加-->
      <div slot="table-bar">
        <RPButton optType="create" @click="add" v-permission="'ROLE_INDEX'" />
        <!-- <RPButton optType="delete" @click="deleted" /> -->
        <!-- <RPButton optType="enable" @click="toggleLock(1)" />
        <RPButton optType="disable" @click="toggleLock(0)" />-->
      </div>
      <Form
        v-if="useTableSearchBar"
        :model="searchForm"
        ref="roleFormSearch"
        slot="table-search-bar"
        label-position="top"
        class="ivu-form-no-margin-bottom"
        inline
      >
        <template>
          <!-- 角色类型 -->
          <Form-item>
            <Select
              style="width: 180px;"
              v-model.trim="searchForm.roleType"
              :placeholder="$t('module.role.warning.selectRoleType')"
              clearable
              @on-change="search(1)"
            >
              <Option v-for="(item, index) in searchRolTypeList" :value="item.vsiKey" :key="index">{{
                item.vsiValue
              }}</Option>
            </Select>
          </Form-item>

          <!-- 状态 -->
          <Form-item prop="enabled">
            <Select
              style="width: 140px;"
              v-model.trim="searchForm.enabled"
              :placeholder="$t('common.warning.selectStatus')"
              @on-change="search(1)"
              clearable
            >
              <Option v-for="(item, index) in searchStatusList" :value="item.vsiKey" :key="index">{{
                item.vsiValue
              }}</Option>
            </Select>
          </Form-item>
          <Form-item prop="searchType">
            <Input
              type="text"
              v-model.trim="searchForm.searchTypeValue"
              :placeholder="searchTypePlaceholder"
              @on-enter="search"
              @on-blur="search"
            >
            <template #prepend>
              <Select v-model="searchForm.searchType" style="width: 110px" @on-change="searchTypeChange">
                <Option v-for="item in searchTypeList" :value="item.key" :key="item.key">{{
                item.name
              }}</Option>
              </Select>
            </template>
            </Input>
          </Form-item>
        </template>
      </Form>
    </InnerPageTable>
  </div>
</template>
<style lang="less"></style>
<script>
import { queryRole, toggleLockRole, deleteByIds } from '@/api/roleApi.js'
import { roleColumns } from './columns.js'
import Three from '@/tools/getThree.js'
// import RoleUserListMg from "./RoleUserListManage.vue";
import RoleDetail from './RoleDetail.vue'
import RoleEdit from './RoleEdit.vue'
import RoleAssignMenu from './RoleAssignMenu.vue'
import PermissionEditForAppRole from './PermissionEditForAppRole.vue'
import RoleAssignApp from './RoleAssignApp.vue'
import RoleAssignDimension from './RoleAssignDimension.vue'
import AuthorizedUser from './AuthorizedUser.vue'
import locales from './locales.js'
import { CoreModuleName } from '@/const.js'
import valueSetAPI from '@/api/valueSetAPI.js'
import { searchAppListByTenantCode } from '@/api/applicationApi.js'

export default {
  name: 'role-manage',
  mixins: [locales],
  data() {
    return {
      useTableSearchBar: false,
      resList: $store.state['ripples-components'].resList,
      category: 1, // 当前登录用户的用户类型
      isQueryMenusAndBtns: false,
      rolePermissonModalTitle: this.$t('module.role.permissionMaList'),
      searchStatusList: [], //状态下拉框数据
      searchRolTypeList: [],
      formInfo: {
        roleName: '',
        remark: '',
        id: '',
        menuIds: '',
        effectBegin: '',
        effectEnd: '',
        roleCode: '',
      },
      searchForm: {
        tenantCode: $store.state[CoreModuleName].userInfo.tenantCode,
        roleName: '',
        roleCode: '',
        roleType: '',
        menuCode: '',
        enabled: 'ALL',
        searchType: 'roleName',
        searchTypeValue: '',
      },
      roleTypeList: {},
      appList: {},
      searchTypeList: [
        {key: 'roleName',  name: this.$t('module.role.roleName'), placeholder: this.$t('module.role.warning.enterRoleName')},
        {key: 'roleCode',  name: this.$t('module.role.roleCode'), placeholder: this.$t('module.role.warning.enterRoleCode')},
        {key: 'menuCode',  name: this.$t('module.role.menuCode'), placeholder: this.$t('module.role.warning.enterMenuCode')},
      ],
      searchTypePlaceholder: this.$t('module.role.warning.enterRoleName'),
    }
  },
  watch: {
    'searchForm.searchType': {
      handler() {
        let selectItem = this.searchTypeList.find(item => item.key == this.searchForm.searchType)
        this.searchTypePlaceholder =  selectItem ? selectItem.placeholder : ''
      }
    }
  },
  computed: {
    tableConfig() {
      return {
        loadDataFn: this.queryRoleList,
        columnsFn: roleColumns.bind(this),
        autoFirst: false,
        rowClassNameFn: this.rowClassName // 自定义行样式
      }
    },
    userRolePermission() {
      if ($store.state['ripples-components'].resList) {
        return $util.checkPermission('ROLE_TYPE_USER')
      }
    },
    appRolePermission() {
      if ($store.state['ripples-components'].resList) {
        return $util.checkPermission('ROLE_TYPE_APP')
      }
    }
  },
  created: function() {
    this.getStateSelect()
  },
  mounted() {
    this.init()
  },
  methods: {
    searchTypeChange() {
      if (this.searchForm.searchTypeValue) {
        this.search()
      }
    },
    // 查看授权用户
    showAuthorizedUser(id, version, row) {
      new this.$pageModal(AuthorizedUser, {
        props: {
          roleId: row.id,
          tenantCode: this.searchForm.tenantCode,
          version: version,
          rowList: row
        }
      })
    },
    // 自定义行样式
    rowClassName(row) {
      //关联的菜单中是否存在有效的hasEnabledMenu:1-存在,0-不存在。enabled:1-有效，0-无效。roleType：1-用户角色，2-应用角色
      if (row.hasEnabledMenu == 0 && row.enabled == 1 && row.roleType == 1) {
        return 'tableDisableStyle'
      }
    },
    // 获取状态下拉数据
    async getStateSelect() {
      const [searchStatusList] = await Promise.all([valueSetAPI.getValueSetByCode('ENABLED_CODE')])
      searchStatusList.map((item, index) => {
        if (item.vsiKey == 'ALL') {
          searchStatusList.splice(index, 1)
        }
      })
      this.searchStatusList = searchStatusList
    },
    async init() {
      let { userInfo } = $store.state[CoreModuleName]
      if (!userInfo) return
      this.category = userInfo.category
      // 根据当前租户查询数据
      this.searchForm.tenantCode = userInfo.tenantCode
      const [roleTypeData, appData] = await Promise.all([
        valueSetAPI.getValueSetByCode('ROLE_TYPE'),
        searchAppListByTenantCode({
          pageNum: 1,
          pageSize: 200,
          condition: {
            tenantCode: this.searchForm.tenantCode
          }
        })
      ])

      // 初始化角色类型
      this.initRoleType(roleTypeData)
      // 查询应用
      this.initApplication(appData)
      // 查询列表
      this.search()
    },
    // 初始化角色类型
    initRoleType(data) {
      // 设置角色类型
      for (const roleType of data) {
        this.roleTypeList[roleType.vsiKey] = roleType.vsiValue
      }
      // 用于查询条件的角色类型，有权限才能查询对应数据。
      // 判断权限：角色类型-用户角色
      if (this.userRolePermission) {
        this.searchRolTypeList.push({
          vsiKey: '1',
          vsiValue: this.$t('module.role.userRoles')
        })
        // 默认查询条件
        // this.searchForm.roleType = "1";
      }
      // 判断权限：角色类型-应用角色
      if (this.appRolePermission) {
        this.searchRolTypeList.push({
          vsiKey: '2',
          vsiValue: this.$t('module.role.applicationRoles')
        })
        // 默认查询条件
        // this.searchForm.roleType = "2";
      }
    },
    initApplication({ data: { records } }) {
      // 查询应用
      records.forEach(app => {
        this.appList[app.clientId] = app.appName
      })
    },
    search(page = 1) {
      let searchParams = Object.assign({}, this.searchForm)

      if(this.useTableSearchBar) {
        this.searchTypeList.forEach(item => {
          if (this.searchForm.searchType == item.key) {
            searchParams[item.key] = this.searchForm.searchTypeValue
          } else {
            searchParams[item.key] = ''
          }
        })
      }
      delete searchParams.searchType
      delete searchParams.searchTypeValue

      if (searchParams.roleType == 'ALL') {
        searchParams.roleType = null
      }
      if (searchParams.enabled == 'ALL') {
        searchParams.enabled = null
      }
      if (this.userRolePermission || this.appRolePermission) {
        this.$refs['roleTable'].load(searchParams, page)
      }
    },
    reset() {
      this.$refs['roleFormSearch'].resetFields()
      if (this.userRolePermission && this.appRolePermission) {
        this.searchForm.roleType = 'ALL'
      }
      this.search(1)
    },
    toggleLock(status) {
      let selectedIds = this.getSelectedIds()
      if (selectedIds.length == 0) {
        this.$message.error({
          content: `${this.$t('module.role.selectWant')}  ${
            status == 0 ? this.$t('common.disable') : this.$t('common.enable')
          } ${this.$t('module.role._role')}`,
          duration: 1.5
        })
        return
      }
      new $confirm(
        `${this.$t('common.confirm')}${status == 0 ? this.$t('common.disable') : this.$t('common.enable')}?`,
        this
      ).then(() => {
        toggleLockRole({ ids: selectedIds, status }).then(res => {
          let tableData = this.$refs['roleTable'].getTableData()
          tableData.forEach(item => {
            if (selectedIds.indexOf(item.id) > -1) {
              item.enabled = status
            }
          })
          // this.search();
        })
      })
    },
    editPermisson(role) {
      if (role.roleType == 2) {
        new this.$pageModal(
          PermissionEditForAppRole,
          {
            props: {
              roleId: role.id,
              roleAppCode: role.appId,
              tenantCode: this.searchForm.tenantCode
            }
          },
          data => {
            data && this.search()
          }
        )
      } else {
        new this.$pageModal(
          RoleAssignMenu,
          {
            props: {
              roleId: role.id,
              roleName: role.roleName,
              roleCode: role.roleCode
            }
          },
          data => {
            data && this.search()
          }
        )
      }
    },
    getOperations(role) {
      let operations = []
      // 其他用户授权的角色只显示“查看详情”，thirdAssignedRole：true为其他用户授权角色,null或false为自建角色
      if (role.thirdAssignedRole == true) {
        operations.push({
          type: 'icon',
          icon: 'ios-eye',
          text: this.$t('common.detail'),
          hidden: role.thirdAssignedRole != true,
          permission: 'ROLE_INDEX',
          handle: () => {
            this.detail(role.id, role)
          }
        })
      } else {
        operations = [
          {
            type: 'icon',
            icon: 'md-create',
            text: this.$t('common.edit'),
            hidden: role.thirdAssignedRole == true,
            permission: 'ROLE_INDEX',
            handle: () => {
              this.edit(role.id, role.version, role)
            }
          }
          // {
          //   type: "icon",
          //   icon: "md-menu",
          //   text: "数据权限",
          //   handle: () => {
          //     this.assignDimension(role);
          //   }
          // }
        ]
        if (role.roleType == 1) {
          operations.push({
            type: 'icon',
            icon: 'ios-settings',
            text: this.$t('module.role.assMeau'),
            hidden: role.thirdAssignedRole == true,
            permission: 'ROLE_INDEX',
            handle: () => {
              this.editPermisson(role)
            }
          })
        } else {
          operations.push({
            type: 'icon',
            icon: 'md-menu',
            text: this.$t('module.role.assResour'),
            hidden: role.thirdAssignedRole == true,
            permission: 'ROLE_INDEX',
            handle: () => {
              this.editPermisson(role)
            }
          })
          operations.push({
            type: 'icon',
            icon: 'ios-hammer',
            text: this.$t('module.role.assignApp'),
            hidden: role.thirdAssignedRole == true,
            permission: 'ROLE_INDEX',
            handle: () => {
              this.assignApp(role)
            }
          })
        }
      }
      // （平台/租户）用户角色的操作列增加“查看授权用户”图标。（应用角色没有）
      if (this.category != 3 && role.roleType == 1) {
        operations.push({
          type: 'icon',
          icon: 'ios-person-add',
          text: this.$t('module.role.authorizedUsers'),
          permission: 'ROLE_INDEX',
          handle: () => {
            this.showAuthorizedUser(role.id, role.version, role)
          }
        })
      }
      return operations
    },
    assignApp(role) {
      new this.$pageModal(
        RoleAssignApp,
        {
          props: {
            roleId: role.id,
            roleName: role.roleName,
            roleCode: role.roleCode,
            appId: role.appId,
            tenantCode: this.searchForm.tenantCode,
            enabled: role.enabled
          }
        },
        data => {}
      )
    },
    assignDimension(role) {
      new this.$pageModal(
        RoleAssignDimension,
        {
          props: {
            roleId: role.id,
            tenantCode: role.tenantCode
          }
        },
        data => {}
      )
    },
    edit(id, version, row) {
      new this.$pageModal(
        RoleEdit,
        {
          props: {
            roleId: id,
            tenantCode: this.searchForm.tenantCode,
            version: version,
            rowList: row
          }
        },
        data => {
          data && this.search(this.$refs.roleTable.param.pageNum)
        }
      )
    },
    detail(id, row) {
      new this.$pageModal(RoleDetail, {
        props: {
          roleId: id,
          rowList: row
        }
      })
    },
    deleted() {
      let selectedIds = this.getSelectedIds()
      if (selectedIds.length == 0) {
        this.$message.error({
          content: this.$t('module.role.warning.selectRole')
        })
        return
      }
      new $confirm(this.$t('module.role.warning.ensureToDelete'), this).then(() => {
        deleteByIds(selectedIds)
          .then(res => {
            this.$message.success({
              content: this.$t('module.orgManage.deleteSuccess'),
              duration: 3
            })
            this.search()
          })
          .catch(data => {
            this.$message.error({
              content: data.message,
              duration: 3
            })
          })
      })
    },
    add() {
      new this.$pageModal(
        RoleEdit,
        {
          props: {
            tenantCode: this.searchForm.tenantCode
          }
        },
        data => {
          data && this.search()
        }
      )
    },
    getSelectedIds() {
      let list = this.$refs['roleTable'].getSelectioned() || []
      let ids = []
      for (let u of list) {
        ids.push(u.id)
      }
      return ids
    },
    getDateString(DateStr) {
      if (DateStr == undefined || DateStr == null || DateStr == '' || DateStr.trim() == '') {
        return ''
      }
      // return DateStr.split(" ")[0];
      let dateList = DateStr.split(' ')[0].split('-')
      let newDateList = []
      let newItem = ''
      for (let key = 0; key < dateList.length; key++) {
        let newNummber = parseInt(dateList[key])
        if (newNummber < 10) {
          newNummber = '0' + newNummber
        }
        newDateList.push(newNummber)
      }
      return newDateList.join('-')
    },
    // 获取角色列表数据
    queryRoleList({ responseProcess, param }) {
      queryRole(param).then(data => {
        responseProcess(data)
      })
    }
  }
}
</script>
<style lang="less">
.RoleManage-page {
  .ivu-table {
    .ivu-table-fixed-right {
      .ivu-table-fixed-body {
        .ivu-table-tbody {
          tr {
            .ivu-table-cell {
              width: 109px !important;
            }
          }
        }
      }
    }
  }
}
</style>
